<?php

namespace Console\Logic;

use Common\Logic\BaseLogic;

class IncomeLogic extends BaseLogic
{
    private $incomeModel;

    public function __construct()
    {
        parent::__construct();
        $this->incomeModel = D('Income');
    }

    /**
     * 为用户发放任务奖金.
     *
     * @param $joinId
     *
     * @return mixed
     */
    public function addTaskIncome($joinId)
    {
        if (empty($joinId)) {
            return static::$res->err('任务凭证不能为空');
        }
        $joinLogic = A('Console/Join', 'Logic');
        $joinInfoRes = $joinLogic->getInfo(array(
            'id' => $joinId,
        ));
        $info = $joinInfoRes['Result'];
        if (empty($info)) {
            return static::$res->err('未找到参与记录');
        }

        //获取参与者用户信息
        $userId = $info['user_id'];
        $userLogic = A('Console/User', 'Logic');
        $userInfoRes = $userLogic->getInfo(array(
            'id' => $userId,
        ));
        $userInfo = $userInfoRes['Result'];

        //判断相同的任务是否已经打过钱
        if (2 == $info['task_type']) {
            $iconWhere = array(
                'user_id' => $info['user_id'],
                'task_id' => $info['task_id'],
            );
            $iconInfo = $this->incomeModel->where($iconWhere)->find();
            if (!empty($iconInfo)) {
                return static::$res->err('相同任务重复打款');
            }
        }

        //判断是否要给推介人分成并计算分成金额
        $parentId = $userInfo['parent_id'];
        $shareIncome = 0;
        if (!empty($parentId)) {
            $recommIncome = (int) $userInfo['recomm_income'];
            //获取分成配置
            $recommLogic = A('Console/Recomm', 'Logic');
            $confRes = $recommLogic->getConfInfo();
            $conf = $confRes['Result'];

            $upper = (int) $conf['upper'];
            if ($recommIncome < $upper) {
                $per = $conf['per'] / 100;
                $shareIncome = $info['income'] * $per;

                if (($shareIncome + $recommIncome) > $upper) {
                    $shareIncome = $upper - $recommIncome;
                }
            }
        }

        //支付给用户
        $data = array(
            'user_id' => $info['user_id'],
            'task_id' => $info['task_id'],
            'task_type' => $info['task_type'],
            'income' => $info['income'],
            'time' => date('Y-m-d H:i:s'),
        );
        $id = $this->incomeModel->add($data);
        if (empty($id)) {
            return static::$res->err('数据库异常，奖金发放失败');
        }

        //支付给推介人
        if ($shareIncome) {
            $data = array(
                'user_id' => $parentId,
                'task_id' => -1,
                'task_type' => 1, //1为收徒
                'income' => $shareIncome,
                'time' => date('Y-m-d H:i:s'),
            );
            $this->incomeModel->add($data);

            $userLogic->updataRecommIncome($userInfo['id'], $shareIncome);
        }

        return static::$res->suc('发放成功');
    }
}
